<template>
	<view class="pwd-retrieve-container">
		<uni-forms ref="form" :value="baseFormData" labelWidth="80px" :rules="dynamicRules">
			
			<uni-forms-item name="userType" label="类型" required>
				<uni-data-checkbox v-model="baseFormData.userType" @change="handleUserType" :localdata="userTypes" />
			</uni-forms-item>
			<view :class="showCompany">
				<uni-forms-item name="company" label="公司" required>
					<uni-easyinput class="uni-mt-5" suffixIcon="scan" disabled v-model="baseFormData.company" placeholder="请点击右侧图标扫描公司二维码" @iconClick="handleScan"></uni-easyinput>
				</uni-forms-item>
			</view>
				
			<uni-forms-item name="nickName" label="姓名" required>
				<uni-easyinput v-model="baseFormData.nickName" placeholder="请输入姓名" />
			</uni-forms-item>
			<uni-forms-item name="birthday" label="出生日期" required>
				<uni-datetime-picker type="date" :clear-icon="false" v-model="baseFormData.birthday" @maskClick="maskClick" />
			</uni-forms-item>
			<uni-forms-item name="sex" label="性别" required>
				<uni-data-checkbox v-model="baseFormData.sex" :localdata="sexs" />
			</uni-forms-item>
			<!-- <view :class="showArea"> -->
			<uni-forms-item name="address" label="地址" required>
				<uni-easyinput v-model="baseFormData.address" placeholder="请输入地址" />
			</uni-forms-item>
			<!-- </view> -->
			<uni-forms-item name="phonenumber" label="手机号" required>
				<uni-easyinput v-model="baseFormData.phonenumber" placeholder="请输入手机号" maxlength="11"/>
			</uni-forms-item>
			<uni-forms-item name="password" label="密码" required>
				<uni-easyinput type="password" v-model="baseFormData.password" placeholder="请输入密码" />
			</uni-forms-item>
			<uni-forms-item name="repassword" label="确认密码" required>
				<uni-easyinput type="password" v-model="baseFormData.repassword" placeholder="请再次输入密码" />
			</uni-forms-item>

			<!-- <text class="tips">注册成功后，请联系管理员分配权限</text> -->
			<button type="primary" size="default" @click="handleRegister">提交</button>
		</uni-forms>

		 <view class="xieyi text-center">
              <text class="text-grey1">注册即代表同意</text>
              <text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
              <text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
         </view>
	</view>
</template>

<script>
import { register, getOpenid } from '@/api/register';
import { getDictByTypeNoAuth } from '@/api/system/dict.js'

export default {
	data() {
		const currentDate = this.getDate({
			format: true
		});
		const _that = this;
		return {
			showCompany: 'show',
			// showArea: 'hide',
			// 基础表单数据
			baseFormData: {
				userType: '2',
				nickName: '',
				birthday: '',
				company: '',
				address: '',
				sex: '0',
				phonenumber: '',
				password: '',
				repassword: '',
				openid: '',
				sessionKey: ''
			},
			userTypes: [
				{
					text: '企业用户',
					value: '2'
				},
				{
					text: '个人用户',
					value: '3'
				}
			],
			// 单选数据源
			sexs: [
				{
					text: '男',
					value: '0'
				},
				{
					text: '女',
					value: '1'
				}
			],
			companyOptions: [], // 公司信息
			//表单校验规则
			dynamicRules: {
				userType: {
					rules: [
						{
							required: true,
							errorMessage: '请选择用户类型'
						}
					]
				},
				nickName: {
					rules: [
						{
							required: true,
							errorMessage: '请输入姓名'
						}
					]
				},
				birthday: {
					rules: [
						{
							required: true,
							errorMessage: '请选择出生日期'
						}
					]
				},
				sex: {
					rules: [
						{
							required: true,
							errorMessage: '请选择性别'
						}
					]
				},
				address: {
					rules: [
						{
							required: true,
							errorMessage: '请输入地址'
						}
					]
				},
				phonenumber: {
					rules: [
						{
							required: true,
							errorMessage: '请输入手机号码',
						},
						{
							minLength: 11,
							maxLength: 11,
							errorMessage: '手机号码为11位',
						},
						{
							validateFunction: function(rule, value, data, callback) {
								let iphoneReg = /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/; //手机号码
								if (!iphoneReg.test(value)) {
									callback('手机号码格式不正确，请重新填写');
								}
							}
						}
					]
				},
				password: {
					rules: [
						{
							required: true,
							errorMessage: '请输入密码',
						}
					]
				},
				repassword: {
					rules: [
						{
							required: true,
							errorMessage: '请再次输入密码',
						},
						{
							validateFunction: function(rule, value, data, callback) {
								if(value !== data.password){
									callback('两次输入的密码不一致!');
								}else {
									callback();
								}
							}
						}
					]
				}
				
		}
		}
	},
	created() {
		// console.log('option', option)
		this.getOrderType();
	},
	onLoad(option) {
		// 页面加载的时候读取下拉数据
		// this.initSelect()
	},
	onReady() {
		// 需要在onReady中设置规则
		this.$refs.form.setRules(this.dynamicRules)
	},
	methods: {
        // 隐私协议
        handlePrivacy() {
            this.$tab.navigateTo(`/pages/mine/agree/index1`)
        },
        // 用户协议
        handleUserAgrement() {
            this.$tab.navigateTo(`/pages/mine/agree/index1`)
        },
		handleScan(){
			const _this = this;
			console.log(this.companyOptions);
			uni.scanCode({
				success: function (res) {
					console.log('条码类型：' + res.scanType);
					console.log('条码内容：' + res.result);
					if (_this.companyOptions.includes(res.result)) {
						_this.baseFormData.company = res.result;
					}else{
						uni.showToast({
						  title: '公司不存在！',
						  icon: 'error'
						})
					}
				}
			});
		},
		// 获取工单类型字典
		getOrderType() {
			getDictByTypeNoAuth('user_company').then(res => {
				// console.log('res', res);
				this.companyOptions = res.data.map(v => {
					return v.dictLabel;
					
				});
			});
		},
		// 处理用户类型
		handleUserType(e) {
			// console.log(e);
			if (e.detail.value == '2') {
				//企业用户
				this.showCompany = 'show';
				// this.showArea = 'hide';
			} else {
				//个人用户
				this.showCompany = 'hide';
				// this.showArea = 'show';
			}
		},
		// 单独校验公司和地址
		validateAddress(){
			let msg = ''
			// 企业用户
			if(this.baseFormData.userType === '2'){
				if(this.$check.isEmpty(this.baseFormData.company)){
					msg = '请选择公司'
				}
			}
			// 个人用户
			if(this.baseFormData.userType === '3'){
				this.baseFormData.company = ""
			}
			return msg;
		},
		submit() {
			setTimeout(() => {
				const _this = this;
				this.$refs.form.validate().then(res => {
						// console.log('表单数据信息：', res);
						// 单独校验公司和地址
						const msg = _this.validateAddress();
						if(!_this.$check.isEmpty(msg)){
							toast(msg);
							return
						}
						register(_this.baseFormData).then(res => {
							// console.log('注册返回结果', res)
							uni.showToast({
								title: '注册成功'
							});
							setTimeout(() => {
								uni.hideToast();
								//关闭提示后跳转
								//'/pages/work/index'
								this.$tab.navigateBack();
								this.$tab.redirectTo('/pages/login/');
								// this.$tab.navigateBack();
							}, 1000);
						})
					})
					.catch(err => {
						console.log('表单错误信息：', err);
					});
			}, 0);
		},
		// 注册
		handleRegister() {
			const _this = this;
			uni.login({
				provider: 'weixin',
				success: function (loginRes) {
					if(loginRes.errMsg === "login:ok"){
						getOpenid(loginRes.code).then(res => {
							// console.log('getOpenid==========11111', res);
							if(res.code === 200){
								_this.baseFormData.sessionKey = res.data.sessionKey
								_this.baseFormData.openid = res.data.openid
							}
							// console.log('getOpenid==========11111', _this.baseFormData);
							_this.submit()
						})
					}else{
						_this.submit()
					}
				}
			});
		},
		getDate(type) {
			const date = new Date();
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let day = date.getDate();

			if (type === 'start') {
				year = year - 60;
			} else if (type === 'end') {
				year = year + 2;
			}
			month = month > 9 ? month : '0' + month;
			day = day > 9 ? day : '0' + day;
			return `${year}-${month}-${day}`;
		}
		
	}
};
</script>

<style lang="scss">
page {
	background-color: #ffffff;
}

.pwd-retrieve-container {
	padding-top: 36rpx;
	padding: 15px;
}

button {
	margin-top: 30rpx;
	margin-bottom: 30rpx;
}

.button-sp-area {
	margin: 0 auto;
	width: 60%;
}

.mini-btn {
	margin-right: 40rpx;
}
.show {
	display: block;
}
.hide {
	display: none;
}
.tips {
	color: red;
}
// .is-td {
//     height: 35px;
//     line-height: 35px;
//   }
// .input-view {
// 	// width: auto;
// 	// position: relative;
// 	// overflow: hidden;
// 	// flex: 1;
// 	// line-height: 1;
// 	// font-size: 14px;
// 	// height: 35px;
// 	height: 35px;
// 	line-height: 35px;
// 	border-radius: 3px;
// 	// border: 1px solid rgba(224, 224, 224, 1);
// 	border: 1px solid rgb(229, 229, 229);
// 	background-color: rgb(255, 255, 255);
// }
.select_view {
	height: 35px;
	line-height: 35px;
	border-radius: 1px;
	// border: 1px solid rgba(224, 224, 224, 1);
	border: 0px solid rgb(229, 229, 229);
	background-color: rgb(255, 255, 255);
}

// .uni-select__selector {
// 	/* #ifndef APP-NVUE */
// 	box-sizing: border-box;
// 	/* #endif */
// 	position: absolute;
// 	top: calc(100% + 12px);
// 	left: 0;
// 	width: 100%;
// 	background-color: #FFFFFF;
// 	border: 1px solid #EBEEF5;
// 	border-radius: 6px;
// 	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
// 	z-index: 99999;
// 	padding: 4px 0;
// }
</style>
